/*
 * @Author: tao
 * @Date: 2019-02-06 23:53:45
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2021-05-18 20:43:38
 * @Func 登录相关的接口信息
 */

const Controller = require("egg").Controller;
const jwt = require("jsonwebtoken");
const svgCaptcha = require("svg-captcha");
class LoginController extends Controller {
  //登录
  async login() {
    try {
      this.ctx.validate({
        user_name: "string",
        user_pwd: "string",
        captcha: "string",
      });
    } catch (err) {
      this.ctx.body = { msg: "参数不完整", code: 0, err };
      return;
    }
    // 验证是否有用户名和密码
    let { user_name, user_pwd, captcha } = this.ctx.request.body;
    user_pwd = this.ctx.helper.sha256(user_pwd);
    if (captcha.toLocaleUpperCase() != this.ctx.cookies.get("captcha").toLocaleUpperCase()) {
      this.ctx.body = { msg: "验证码错误", code: 0 };
      return;
    }
    let userResult = await this.app.mysql.select("user", {
      where: { user_name },
    });
    if (userResult === 0) {
      this.ctx.body = { msg: "用户不存在", code: 0 };
      return;
    }
    if (userResult[0].user_pwd !== user_pwd) {
      this.ctx.body = { msg: "密码不正确", code: 0 };
      return;
    }
    let { user_id, identity_id } = userResult[0];
    let identityResult = await this.app.mysql.select("identity", {
      where: { identity_id },
    });
    let identity_text = identityResult[0].identity_text;
    let userInfo = {
      signTime: new Date().getTime(),
      user_id,
      user_name,
      identity_id,
      identity_text,
    };
    // 签发token
    let token = jwt.sign(userInfo, this.ctx.helper.createKeys());
    this.ctx.body = { msg: "登录成功", code: 1, token, userInfo };
  }
}
module.exports = LoginController;
